package de.matusystems

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.net.URL;
import java.net.URLConnection;


import groovy.json.JsonSlurper

class HomeController {

	def newsletterService

	def storageWebService

	def index = { log.info("registration controller called") }

	def register = { RegistrationCommand cmd ->
		if (cmd.hasErrors()) {
			render(view: 'index', model:[registrationCommand:cmd])
			return
		}

		def jsonResult = newsletterService.registerUser(cmd.firstname, cmd.lastname, cmd.email)

		JsonSlurper slurper = new JsonSlurper()
		def result = slurper.parseText(jsonResult.toString())
		def userId = result['data']['id']
		new SignUp(userId:userId).save(flush:true)
		[userId:userId, firstname:cmd.firstname, lastname:cmd.lastname, email:cmd.email]
	}

	def thumbnail = {

		// get content from service (content could be the last 5 movies release)
		// content contains movie description and a big size movie poster

		def fileToDownload = params['url']

		URL url = new URL("http://matusewicz-image-transform.appspot.com/img_service_gae?url="+fileToDownload+"&action=resize&width=300&height=300");
		URLConnection urlc = url.openConnection();

		BufferedInputStream bis = new BufferedInputStream(urlc.getInputStream());
		ByteArrayOutputStream baos = new ByteArrayOutputStream();

		int i;
		while ((i = bis.read()) != -1) {
			baos.write(i);
		}

		byte[] file = baos.toByteArray();

		render storageWebService.saveFile("thumbnail", "image/jpeg", file);

	}

	def sendNewsletterToUsers = {
	}
}

class RegistrationCommand {
	String firstname
	String lastname
	String email

	static constraints = {
		firstname(blank: false, minSize: 2)
		lastname(blank: false, minSize: 2)
		email(blank:false, email:true)
	}
}